package cn.vcjf.weapp.common.wxpay;

import cn.vcjf.weapp.common.util.SysParamUtil;
import cn.vcjf.weapp.common.wxpay.sdk.WXPayConfigImpl;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: zhengzihang
 * @Date: 2018/7/12 11:12
 * @Description:微信官方公众号 支付
 */

public abstract class AbstractWxPayAuth extends HttpServlet {

	private Logger logger = LogManager.getLogger(AbstractWxPayAuth.class);

	public static String BASE_URL=SysParamUtil.getParam("online.base.common.callbackurl");//"http://vcjf.s1.natapp.cc/";//

	//开发者密码
	public static String APP_SECRET = "31a3e5ef4773eadd05ce1a1418eb2c9a";

	/**
	 * 下单url
	 * @return
	 */
	protected abstract String getUnifiedOrderUrl();
	/**
	 * 当前servlet的url,用来授权重定向
	 * @return
	 */
	protected abstract String getThisServletUrl();

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String queryString = request.getQueryString();
		logger.info("微信公众号下单请求参数:{}",queryString);
		//检查参数
		try {
			doCheckRequestParams(request);

			String openId = WxPayAuthApi.getCode(request, response, WXPayConfigImpl.APP_ID, APP_SECRET
					, BASE_URL + getThisServletUrl() + "?" + queryString
			);
			if ("".equals(openId)) {
				response.getWriter().print("获取openId失败");
			}
			if (openId != null) {
				response.sendRedirect(BASE_URL + getUnifiedOrderUrl() + "?openId="+openId+"&" + queryString);
			}
		} catch (Exception e) {
			logger.error("微信公众号下单请求异常:{}",e.getMessage());
		}
		return;
	}

	protected abstract void doCheckRequestParams(HttpServletRequest request);

	public void setHttpServletContent(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=utf-8");
	}
}
